package com.mibsvc.appsvc.req;

import com.alibaba.fastjson.JSONObject;
import com.mibsvc.appsvc.util.AesCbcUtil;
import com.mibsvc.appsvc.util.Result;
import com.mibsvc.appsvc.util.WxUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WxController {


    @GetMapping("/signature")
    public String signature(String signature, String timestamp, String nonce, String echostr) {
        // 微信加密签名
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (WxUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.print("echostr=" + echostr);
            return echostr;
        }else{
            return null;
        }
    }

    @PostMapping("/getOpenId")
    public Object getOpenId(String iv, String encryptedData, String code) {
        Map map = new HashMap();
        try {
            if (code == null || code.length() == 0) {
                return new Result(1, "wechat.getOpenIdNull");
            }
            String wechatAppId = "wxf05661d3a96a6a4c";
            String wechatSecretKey = "c0179c98f7e2e0e3bc3aa79ba7b2f0cb";
            String grantType = "authorization_code";
            String params = "appid=" + wechatAppId + "&secret=" + wechatSecretKey + "&js_code=" + code + "&grant_type=" + grantType;
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            String sr = sendGet(url, params);
            System.out.println(sr);
            JSONObject json = JSONObject.parseObject(sr);
            String sessionKey = json.get("session_key").toString();
            String openId = json.get("openid").toString();
            String result = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                JSONObject userInfoJSON = JSONObject.parseObject(result);
                Map userInfo = new HashMap();
                userInfo.put("openId", userInfoJSON.get("openId"));
                userInfo.put("nickName", userInfoJSON.get("nickName"));
                userInfo.put("gender", userInfoJSON.get("gender"));
                userInfo.put("city", userInfoJSON.get("city"));
                userInfo.put("province", userInfoJSON.get("province"));
                userInfo.put("country", userInfoJSON.get("country"));
                userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
                userInfo.put("unionId", userInfoJSON.get("unionId"));

                Map resultMap = new HashMap();
                if (userInfoJSON.get("openId") != null) {
                    resultMap.put("resultCode", "success");
                } else {
                    resultMap = new HashMap();
                    resultMap.put("openId", userInfoJSON.get("openId").toString());
                    resultMap.put("resultCode", "error");
                }
                map.put("userInfo", userInfo);
                map.put("loginInfo", resultMap);
                return Result.success("success", map);
            }
        } catch (Exception e) {
            return Result.error("error");
        }
        return new Result(1, "wechat.getOpenIdFailed");
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}
